<?php

namespace App\Imports;

use App\Models\User\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DemoImport extends CommonImport
{

    public function __construct(array $params=[]) {
        $this->params = $params;
        $this->instance = new User();
    }

    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        $this->count = $collection->count();
        $time = date('Y-m-d H:i:s');

        foreach ($collection as $k=>$v) {
            if($k<=0)continue;//过滤表头
            $v = $v->toArray();
            if(count(array_filter($v))<=0){continue;}

            //组装数据
            $this->records[] = [
                ''=>$v[0],
                ''=>$v[1],
                ''=>$v[2],
                ''=>$v[3],
                ''=>$v[4],
                ''=>$v[5],

                'created_at'=>$time,
                'updated_at'=>$time
            ];

            $this->countSuccess++;
            dump($this->countSuccess);
        }
        try{
            DB::beginTransaction();

            $this->instance->insert($this->records);

            DB::commit();
            $this->msg = "本次导入共：".$this->count.'条数据，成功：'.$this->countSuccess.'条，失败：'.$this->countFail.'条';
            return true;
        }catch(\Exception $e){
            DB::rollback();
            $this->success = false;
            $this->msg = $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return false;
        }



    }
}
